<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="商品名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入商品名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="商品类型" prop="type">
        <el-select v-model="queryParams.type" placeholder="请选择商品类型" clearable>
          <el-option
            v-for="dict in dict.type.product_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['supply:prodinfo:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['supply:prodinfo:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['supply:prodinfo:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['supply:prodinfo:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="prodinfoList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="主键商品ID" align="center" prop="id" />
      <el-table-column label="商品名称" align="center" prop="name" />
      <el-table-column label="商品图片" align="center" prop="imageUrl" width="100">
        <template slot-scope="scope">
          <image-preview :src="scope.row.imageUrl" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <el-table-column label="商品类型" align="center" prop="type">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.product_type" :value="scope.row.type"/>
        </template>
      </el-table-column>
      <el-table-column label="商品品牌" align="center" prop="brand" />
      <el-table-column label="最小单位" align="center" prop="minUnit" />
      <el-table-column label="商品性质" align="center" prop="nature" />
      <el-table-column label="库存数量" align="center" prop="stockQuantity" />
      <el-table-column label="单价" align="center" prop="unitPrice" />
      <!-- 新增手续费列 -->
      <el-table-column label="手续费" align="center" prop="handlingFee">
        <template slot-scope="scope">
          <span>{{ scope.row.handlingFee || '0.00' }}</span>
          <pre>{{ scope.row }}</pre> <!-- 临时添加，用于查看每条记录的所有字段 -->
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.product_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.status !=0 "
            size="mini"
            type="text"
            @click="StatusUpdate(scope.row)"
            v-hasPermi="['supply:prodinfo:edit']"
          >禁用</el-button>
          <el-button
            v-else
            size="mini"
            type="text"
            @click="StatusUpdate(scope.row)"
            v-hasPermi="['supply:prodinfo:edit']"
          >启用</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['supply:prodinfo:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['supply:prodinfo:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改商品信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="商品名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入商品名称" />
        </el-form-item>
        <el-form-item label="商品图片" prop="imageUrl">
          <image-upload v-model="form.imageUrl"/>
        </el-form-item>
        <el-form-item label="商品类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择商品类型">
            <el-option
              v-for="dict in dict.type.product_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="商品品牌" prop="brand">
          <el-input v-model="form.brand" placeholder="请输入商品品牌" />
        </el-form-item>
        <el-form-item label="最小单位" prop="minUnit">
          <el-input v-model="form.minUnit" placeholder="请输入最小单位" />
        </el-form-item>
        <el-form-item label="商品性质" prop="nature">
          <el-input v-model="form.nature" placeholder="请输入商品性质" />
        </el-form-item>
        <el-form-item label="库存数量" prop="stockQuantity">
          <el-input v-model="form.stockQuantity" placeholder="请输入库存数量" />
        </el-form-item>
        <el-form-item label="单价" prop="unitPrice">
          <el-input v-model="form.unitPrice" placeholder="请输入单价" @input="calculateAmount" />
        </el-form-item>
        <!-- 仅在“添加商品”弹窗中显示手续费和到手金额 -->
        <el-form-item v-if="title === '添加商品信息'" label="手续费">
          <span>{{ handlingFee || '0.00' }}</span>
        </el-form-item>
        <el-form-item v-if="title === '添加商品信息'" label="到手金额">
          <span>{{ netAmount || '0.00' }}</span>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listProdinfo, getProdinfo, delProdinfo, addProdinfo, updateProdinfo } from "@/api/supply/prodinfo";
import { getUserProfile } from "@/api/system/user";
import { getRate } from "@/api/supply/prodinfo";

export default {
  name: "Prodinfo",
  dicts: ['product_type', 'product_status'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 商品信息表格数据
      prodinfoList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        type: null,
        status: null,
        supplierId: null
      },
      // 表单参数
      form: {},
      // 手续费和到手金额
      handlingFee: '0.00',
      netAmount: '0.00',
      // 手续费率（用于计算）
      rate: null,
      // 表单校验
      rules: {
        name: [
          { required: true, message: "商品名称不能为空", trigger: "blur" }
        ],
        type: [
          { required: true, message: "商品类型不能为空", trigger: "change" }
        ],
        unitPrice: [
          { required: true, message: "单价不能为空", trigger: "blur" },
          { pattern: /^\d+(\.\d{1,2})?$/, message: "请输入有效金额（最多两位小数）", trigger: "blur" }
        ]
      },
      // 用户信息
      user: {}
    };
  },
  created() {
    console.log('Component created, calling getList'); // 确认 created 钩子执行
    this.getList();
  },
  methods: {
    /** 查询商品信息列表 */
    async getList() {
      console.log('getList method called'); // 确认方法执行
      this.loading = true;
      try {
        // 获取手续费率
        console.log('Fetching rate...');
        const response = await getRate();
        console.log('getRate response in getList:', response);
        this.rate = parseFloat(response);
        console.log('手续费比率 (getList):', this.rate); // 输出手续费比率
        if (isNaN(this.rate) || this.rate < 0) {
          throw new Error('无效的手续费比例');
        }

        // 获取用户信息
        console.log('Fetching user profile...');
        const userResponse = await getUserProfile();
        console.log('getUserProfile response:', userResponse);
        this.user = userResponse.data;
        this.queryParams.supplierId = this.user.userId;

        // 获取商品列表
        console.log('Fetching product list...');
        const prodResponse = await listProdinfo(this.queryParams);
        console.log('listProdinfo response:', prodResponse);
        this.prodinfoList = prodResponse.rows.map(item => {
          const unitPrice = parseFloat(item.unitPrice);
          const handlingFee = (isNaN(unitPrice) || unitPrice <= 0) ? '0.00' : (unitPrice * this.rate).toFixed(2);

          // 使用Vue.set确保响应式更新
          this.$set(item, 'handlingFee', handlingFee);

          console.log(`unitPrice: ${unitPrice}, rate: ${this.rate}, handlingFee: ${handlingFee}`);
          return {
            ...item,
            handlingFee // 确保字段被包含
          };
        });
        console.log('Final prodinfoList:', this.prodinfoList); // 打印最终列表
        this.total = prodResponse.total;
        this.loading = false;
      } catch (error) {
        console.error('获取商品列表或手续费率失败:', error);
        console.error('Error details:', error.message, error.stack); // 打印详细错误信息
        this.$message.error('无法加载商品列表，请稍后重试');
        this.rate = null; // 重置手续费率
        this.prodinfoList = []; // 清空列表
        this.total = 0;
        this.loading = false;
      }
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        imageUrl: null,
        type: null,
        brand: null,
        minUnit: null,
        nature: null,
        supplierId: null,
        stockQuantity: null,
        unitPrice: null,
        remark: null
      };
      this.handlingFee = '0.00';
      this.netAmount = '0.00';
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加商品信息";
      this.$nextTick(() => {
        this.calculateAmount(); // 确保初始计算
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getProdinfo(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改商品信息";
        this.$nextTick(() => {
          this.calculateAmount(); // 仍然计算，但不显示
        });
      });
    },
    // 状态修改
    StatusUpdate(row) {
      getProdinfo(row.id).then(response => {
        this.form = response.data;
        if (this.form.status != 0) {
          this.form.status = 0;
          if (this.form.id != null) {
            updateProdinfo(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.getList();
            });
          }
        } else {
          this.form.status = 2;
          if (this.form.id != null) {
            updateProdinfo(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.getList();
            });
          }
        }
      });
    },
    /** 计算手续费和到手金额（用于弹窗） */
    async calculateAmount() {
      console.log('calculateAmount triggered, unitPrice:', this.form.unitPrice);
      const unitPrice = parseFloat(this.form.unitPrice);
      if (isNaN(unitPrice) || unitPrice <= 0) {
        this.handlingFee = '0.00';
        this.netAmount = '0.00';
        console.log('Invalid unitPrice, resetting:', this.handlingFee, this.netAmount);
        return;
      }
      try {
        let rate = this.rate;
        if (rate === null) {
          console.log('Fetching rate in calculateAmount...');
          const response = await getRate();
          console.log('getRate response in calculateAmount:', response);
          rate = parseFloat(response);
          this.rate = rate;
          console.log('手续费比率 (calculateAmount):', rate);
          if (isNaN(rate) || rate < 0) {
            throw new Error('无效的手续费比例');
          }
        }
        this.handlingFee = (unitPrice * rate).toFixed(2);
        this.netAmount = (unitPrice - parseFloat(this.handlingFee)).toFixed(2);
        console.log('Calculated:', { handlingFee: this.handlingFee, netAmount: this.netAmount, rate });
      } catch (error) {
        console.error('获取手续费率失败 (calculateAmount):', error);
        console.error('Error details:', error.message, error.stack);
        this.handlingFee = '0.00';
        this.netAmount = '0.00';
        this.$message.error('无法获取手续费比例，请稍后重试');
      }
    },
    /** 提交按钮 */
    async submitForm() {
      this.$refs["form"].validate(async valid => {
        if (valid) {
          this.form.status = 2;
          try {
            let rate = this.rate;
            if (rate === null) {
              console.log('Fetching rate in submitForm...');
              const response = await getRate();
              console.log('++++++++++++++++++++++', response);
              rate = parseFloat(response);
              this.rate = rate;
              console.log('手续费比率 (submitForm):', rate);
              if (isNaN(rate) || rate < 0) {
                throw new Error('无效的手续费比例');
              }
            }
            this.$message.info(`本次上架物品手续费比例为: ${(rate * 100).toFixed(2)}%`);

            if (this.form.id != null) {
              await updateProdinfo(this.form);
              this.$modal.msgSuccess("修改成功");
            } else {
              this.form.supplierId = this.user.userId;
              await addProdinfo(this.form);
              this.$modal.msgSuccess("新增成功");
            }
            this.open = false;
            this.getList();
          } catch (error) {
            console.error('提交失败:', error);
            console.error('Error details:', error.message, error.stack);
            this.$modal.msgError("操作失败，请检查网络或稍后重试");
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除商品信息编号为"' + ids + '"的数据项？').then(() => {
        return delProdinfo(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('supply/prodinfo/export', {
        ...this.queryParams
      }, `prodinfo_${new Date().getTime()}.xlsx`);
    }
  }
};
</script>
